package com.hoshiicloud.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.query.OmnipotentParam;
import com.hoshiicloud.common.query.OmnipotentWrapper;
import com.hoshiicloud.common.update.UpdateBatchParam;
import com.hoshiicloud.goods.entity.category.SalesCategory;
import com.hoshiicloud.goods.entity.spu.ExtSpuTags;
import com.hoshiicloud.goods.entity.spu.SpuSalesCategory;
import com.hoshiicloud.goods.feign.IdGeneratorService;
import com.hoshiicloud.goods.mapper.spu.ExtSpuTagsMapper;
import com.hoshiicloud.goods.service.ExtSpuTagsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * SPU服务标签 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-04
 */
@Slf4j
@Service
public class ExtSpuTagsServiceImpl extends ServiceImpl<ExtSpuTagsMapper, ExtSpuTags> implements ExtSpuTagsService {

    @Autowired
    private IdGeneratorService idGeneratorService;

    /**
     * @param id
     * @return ExtSpuTags
     * @description: 根据id查询SPU服务标签
     */
    @Override
    @Cacheable(cacheNames = "ExtSpuTags", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "商品管理-SPU服务标签-查询SPU服务标签 ")
    public ExtSpuTags getById(Long id) {
        return baseMapper.selectById(id);
    }


    /**
     * @param entity
     * @return boolean
     * @description: 新增SPU服务标签
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ExtSpuTags", allEntries = true)
    @Logable(authName = "商品管理-SPU服务标签-新增SPU服务标签")
    public boolean save(ExtSpuTags entity) {

        // 生成主键ID
        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }

        // 新增数据
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return true;
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改SPU服务标签
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ExtSpuTags", allEntries = true)
    @Logable(authName = "商品管理-SPU服务标签管理-修改SPU服务标签")
    public boolean updateById(ExtSpuTags entity) {

        // 更新数据
        entity.setUpdatedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }

    /**
     * @param queryWrapper 查询条件
     * @return IPage
     * @description: 分页查询SPU服务标签
     */
    @Override
    @Logable(authName = "商品管理-SPU服务标签管理-分页查询SPU服务标签")
    @Cacheable(cacheNames = "ExtSpuTags", key = "T(com.hoshiicloud.common.utils.DigestUtils).md5(#root.targetClass.simpleName+':'+#root.methodName+':'+#key)")
    public IPage getPage(IPage page, Wrapper queryWrapper, String key) {
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ExtSpuTags", allEntries = true)
    @Logable(authName = "商品管理-SPU服务标签管理-删除SPU服务标签")
    public boolean deleteById(Long id) {

        // 根据id查询数据
        ExtSpuTags entity = this.getById(id);
        if (entity == null) {
            throw new ServiceException("删除SPU服务标签异常，无法找到SPU服务标签记录");
        }

        //进行删除操作
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        }
        return true;
    }

    @Override
    @Cacheable(cacheNames = "ExtSpuTags", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "商品管理-SPU服务标签管理-根据id集合查询SPU服务标签")
    public List<ExtSpuTags> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }

    @CacheEvict(cacheNames = "ExtSpuTags", allEntries = true)
    @Logable(authName = "删除商品的标签信息")
    @Override
    public boolean removeTagsById(Long id) {
        // 根据id查询数据
        ExtSpuTags entity = this.getById(id);
        if (entity == null) {
            throw new ServiceException("删除SPU服务标签异常，无法找到SPU服务标签记录");
        }
        return this.removeById(id);
    }

    /**
     * 根据spuId获取标签
     *
     * @param spuId 商品SPU主键
     * @return List<ExtSpuTags>
     */
    @Cacheable(cacheNames = "ExtSpuTags", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#spuId")
    @Logable(authName = "商品管理-SPU服务标签管理-根据spuId获取标签")
    @Override
    public List<ExtSpuTags> getBySpuId(Long spuId) {
        try {
            QueryWrapper<ExtSpuTags> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("spu_id", spuId);
            queryWrapper.eq("deleted", 0);
            return baseMapper.selectList(queryWrapper);
        } catch (Exception e) {
            log.error("根据spuId获取标签异常" + "[" + e.getMessage() + "]");
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 批量新增SPU服务标签
     */
    @Override
    @CacheEvict(cacheNames = "ExtSpuTags", allEntries = true)
    @Logable(authName = "批量新增SPU服务标签")
    public boolean saveTagsBatch(List<ExtSpuTags> extSpuTags) {
        boolean isTrue = this.saveBatch(extSpuTags);
       if (!isTrue) {
            throw new ServiceException("新增spu服务标签失败！");
        }
        return true;
    }

    @Override
    public List<ExtSpuTags> listBySpuIds(List<Long> spuIds) {
        QueryWrapper<ExtSpuTags> q = new QueryWrapper<>();
        q.lambda().in(ExtSpuTags::getSpuId,spuIds).eq(ExtSpuTags::getDeleted,0);
        return baseMapper.selectList(q);
    }

    /**
     * 根据SpuId批量删除
     */
    @Override
    @CacheEvict(cacheNames = "ExtSpuTags", allEntries = true)
    public Boolean deleteBatchs(Long extSpuId) {
        QueryWrapper<ExtSpuTags> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ExtSpuTags::getSpuId, extSpuId).eq(ExtSpuTags::getDeleted, 0);

        ExtSpuTags update = new ExtSpuTags();
        update.setDeleted(1);

        baseMapper.update(update, wrapper);
        return true;
    }

    @CacheEvict(cacheNames = "ExtSpuTags", allEntries = true)
    @Logable(authName = "根据自定义条件批量更新")
    @Override
    public boolean updateBatchByWrapper(UpdateBatchParam<ExtSpuTags> updateBatchParam) {
        ExtSpuTags updateEntity = updateBatchParam.getUpdateEntity();
        QueryWrapper<ExtSpuTags> wrapper = updateBatchParam.getWrapper();
        return this.update(updateEntity, wrapper);
    }

    /**
     * 批量更新
     */
    @Override
    @CacheEvict(cacheNames = "ExtSpuTags", allEntries = true)
    @Logable(authName = "批量更新")
    public Boolean updateBatch(OmnipotentParam<ExtSpuTags> param) {
        List<OmnipotentWrapper> wrappers = param.getWrappers();
        OmnipotentWrapper<ExtSpuTags> wrapper = new OmnipotentWrapper<>();
        UpdateWrapper<ExtSpuTags> updateWrapper = wrapper.getUpdateWrapper(wrappers);
        ExtSpuTags entity = param.getEntity();
        return this.update(entity, updateWrapper);
    }


    @Override
    @CacheEvict(cacheNames = "ExtSpuTags", allEntries = true)
    @Logable(authName = "批量删除商品标签信息: 物理删除")
    public Boolean removeBatch(List<OmnipotentWrapper> param) {
        OmnipotentWrapper<ExtSpuTags> wrapper = new OmnipotentWrapper<>();
        QueryWrapper<ExtSpuTags> queryWrapper = wrapper.getWrapper(param);
        return this.remove(queryWrapper);
    }

}
